package com.apptest.android.ui.navigation;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apptest.android.R;
import com.apptest.android.core.bean.NavigationTagBean;
import com.apptest.android.databinding.FragmentNavigationBinding;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;

import java.util.List;

import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.adapter.TabAdapter;
import q.rorbin.verticaltablayout.widget.ITabView;
import q.rorbin.verticaltablayout.widget.TabView;

public class NavigationFragment extends Fragment {

    private NavigationViewModel navigationViewModel;
    private FragmentNavigationBinding binding;
    private NavigationAdapter navigationAdapter;
    private LinearLayoutManager navigationGroupLayoutManager;
    private int currIndex;
    private boolean needScroll;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        navigationViewModel =
                new ViewModelProvider(this).get(NavigationViewModel.class);
        binding = FragmentNavigationBinding.inflate(inflater, container, false);
        navigationGroupLayoutManager = new LinearLayoutManager(
                getActivity(), LinearLayoutManager.VERTICAL, false
        );
        initView();
        linkLayout();
        return binding.getRoot();
    }

    private void initView(){
        navigationViewModel.getNavigationList().observe(getViewLifecycleOwner(),
                list -> {
                    navigationAdapter = new NavigationAdapter(R.layout.item_navigation_group,
                            navigationViewModel.getNavigationList().getValue());
                    binding.navigationGroupLayout.setAdapter(navigationAdapter);
                    binding.navigationGroupLayout.setLayoutManager(navigationGroupLayoutManager);
                    binding.navigationTabLayout.setTabAdapter(new TabAdapter() {
                        @Override
                        public int getCount() {
                            return list == null ? 0 : list.size();
                        }
                        @Override
                        public ITabView.TabBadge getBadge(int i) {
                            return null;
                        }
                        @Override
                        public ITabView.TabIcon getIcon(int i) {
                            return null;
                        }
                        @Override
                        public ITabView.TabTitle getTitle(int i) {
                            return new TabView.TabTitle.Builder()
                                    .setContent(list.get(i).getName())
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.colorAccent),
                                            ContextCompat.getColor(getContext(), R.color.Grey500))
                                    .build();
                        }

                        @Override
                        public int getBackground(int i) {
                            return -1;
                        }
                    });
                });

    }

    private void linkLayout() {
        binding.navigationGroupLayout.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(needScroll&&newState==RecyclerView.SCROLL_STATE_IDLE){//左部标签页请求调整
                    scrollNavigationGroup();
                }
                selectTag(newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(needScroll)
                    scrollNavigationGroup();
            }
        });

        binding.navigationTabLayout.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tabView, int i) {
                scrollNavigationGroupToPosition(i);
            }

            @Override
            public void onTabReselected(TabView tabView, int i) {
            }
        });
    }

    private void selectTag(int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            int firstPosition = navigationGroupLayoutManager.findFirstVisibleItemPosition();
            if(currIndex!=firstPosition){
                currIndex = firstPosition;
                binding.navigationTabLayout.setTabSelected(currIndex);
            }
        }
    }

    private void scrollNavigationGroup(){
        needScroll = false;
        int indexDistance = currIndex - navigationGroupLayoutManager.findFirstVisibleItemPosition();
        if (indexDistance >= 0 && indexDistance < binding.navigationGroupLayout.getChildCount()) {
            int top = binding.navigationGroupLayout.getChildAt(indexDistance).getTop();
            binding.navigationGroupLayout.smoothScrollBy(0, top);
        }
    }

    private void scrollNavigationGroupToPosition(int position) {
        currIndex = position;
        binding.navigationGroupLayout.stopScroll();
        int firstPosition = navigationGroupLayoutManager.findFirstVisibleItemPosition();
        int lastPosition = navigationGroupLayoutManager.findLastVisibleItemPosition();
        if (position <= firstPosition) {
            binding.navigationGroupLayout.smoothScrollToPosition(position);
        } else if (position <= lastPosition) {
            int top = binding.navigationGroupLayout.getChildAt(position - firstPosition).getTop();
            binding.navigationGroupLayout.smoothScrollBy(0, top);
        } else {
            binding.navigationGroupLayout.smoothScrollToPosition(position);
            needScroll = true;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}